package com.yinhe.overtimecalc.server;

import java.io.IOException;
import java.net.*;

public class UdpClient extends ServerClient{

    DatagramSocket dSocket;
    InetAddress sAddr;

    public UdpClient(){
        try {
            dSocket = new DatagramSocket();
//            if (args.length == 0){
//                sAddr = InetAddress.getByName("127.0.0.1");
//            }else{
//                sAddr = InetAddress.getByName(args[0]);
//            }
            sAddr = InetAddress.getByName(IP);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendMessage(String s){
        byte[] outBuffer = s.getBytes();
        DatagramPacket outPacket = new DatagramPacket(outBuffer,outBuffer.length,sAddr,PORT);
        try {
            dSocket.send(outPacket);//发送数据
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getMessage(){
        byte[] inBuffer = new byte[100];
        DatagramPacket  inPacket = new DatagramPacket(inBuffer,inBuffer.length);
        try {
            dSocket.receive(inPacket);//接收数据
        } catch (IOException e) {
            e.printStackTrace();
        }
        String s = new String(inPacket.getData(),0,inPacket.getLength());
        System.out.println("接收到服务器端信息："+s);
        return  s;
    }

    @Override
    public void close(){
        if (dSocket!=null){
            dSocket.close();
        }
    }
}
